// Global Vars
var currentSection = '';
var sections = ['videos', 'polls'];
var questionsResponse = '';
var currentPoll = 0;
var votedPolls = [];
var VIDEOS = [];
var currentPage = 0;
var lang = 'en';

// Initialise Functions
function init()
{
	if($("#comp_gadget").get(0).contentDocument)
	{
		$("#comp_gadget").load(function(){
			$("#comp_gadget").get(0).contentDocument.getElementById("ytcp-home").style.backgroundColor = 'transparent';
			$("#comp_gadget").get(0).contentDocument.getElementById("ytcp-home").style.border = 'none';
			$("#comp_gadget").get(0).contentDocument.getElementById("ytcp-home-links").getElementsByTagName('a').item(0).onclick=function(){
				window.changeSection('polls');
				return false;
			}
		});
	}
	else
	{		
		$("#comp_gadget").load(function(){
			$("#comp_gadget").get(0).contentWindow.document.getElementById("ytcp-home").style.backgroundColor = 'transparent';
			$("#comp_gadget").get(0).contentWindow.document.getElementById("ytcp-home").style.border = 'none';
			$("#comp_gadget").get(0).contentWindow.document.getElementById("ytcp-home-links").getElementsByTagName('a').item(0).onclick=function(){
				window.changeSection('polls');
				return false;
			}
		});
	}

	changeSection('videos');

	switch(lang)
	{
		case 'en':
			var loadingTxt = 'Loading...';
			break;
		case 'fr':
			var loadingTxt = 'Chargement...';
			break;
		case 'de':
			var loadingTxt = 'Wird geladen...';
			break;
	}

	$('.loader').html(loadingTxt);

	votedPolls[0] = 0;
	votedPolls[1] = 0;
	votedPolls[2] = 0;
	votedPolls[3] = 0;

}

// Hide Sectioms
function hideSections()
{
	for(var i=0;i<sections.length;i++)
	{
		$('#menu_'+sections[i]).removeClass('activeTab');
		$('#menu_'+sections[i]).addClass('inactiveTab');
	}

	currentSection = '';

	return false;
}

// Change To Section
function changeSection(section)
{
	if (currentSection == section)
	{
		return false;
	}

	hideSections();

	$('#menu_'+section).removeClass('inactiveTab'); 
	$('#menu_'+section).addClass('activeTab');

	currentSection = section;

	// Use this switch to set any onload events for specific sections
	switch(section)
	{
		case 'polls':
			getQuestions();
			break;
		case 'videos':
			initVideos();
			break;
	}

	return false;
}

// Initialise the videos tab!
function initVideos()
{
	if (VIDEOS.length < 1)
	{
		// Fetch Data
		$('#videos .loader').fadeIn(200);
		fetchPlaylist(function(response)
		{
			youtube.parsePlaylist(response, function(data)
			{
				VIDEOS = data;
				refreshVideoPaging();
				displayVideos();
				playVideo(VIDEOS[0], 0);
			});
		});
	}
}

function refreshVideoPaging()
{
	var videoCount = VIDEOS.length;
	var videoPages = (Math.ceil(VIDEOS.length / 6) - 1);

	if (currentPage <= 0)
	{
		$('#videos .previous').unbind('click').hide();
	}
	else
	{
		$('#videos .previous').unbind('click').click(function(){changeVideoPage('previous'); return false;}).show();
	}

	if (currentPage < videoPages)
	{
		$('#videos .next').unbind('click').click(function(){changeVideoPage('next'); return false;}).show();
	}
	else
	{
		$('#videos .next').unbind('click').hide();
	}
}

function changeVideoPage(direction)
{
	var pageHeight = ($('.videoList ul li').outerHeight(true) * 3);

	switch(direction)
	{
		case 'next':
			currentPage ++;
			break;
		case 'previous':
			currentPage --;
			break;
	}

	$('.videoList ul').animate({top:'-'+pageHeight*currentPage+'px'}, 200, "swing", function(){
		refreshVideoPaging();
		stupidIeMenuHack();
	});
}

function playVideo(video, ap)
{
	if(ap == undefined)
	{
		var ap = 1;
	}

	_IG_EmbedFlash(video.VideoSwfUrl, 'mainVideoContainer', {width: 640, height: 385, flashvars: "autoplay="+ap});
	
	stupidIeMenuHack();

	return false;
}

function stupidIeMenuHack()
{
	// The most STUPID IE7 hack ever!!!! And it doesn't even fix IE6
	setTimeout(function(){
		$('#menu_polls .pollPanel h2, #menu_polls .pollPanel h2 a, #menu_polls, #menu_polls .pollPanel').css('display', 'block');

		setTimeout(function(){
			$('#menu_polls .pollPanel h2, #menu_polls .pollPanel h2 a, #menu_polls, #menu_polls .pollPanel').css('display', '');
		},1);
	}, 1);
}

function displayVideos()
{
	$('#videos .loader').fadeOut(200);

	if (VIDEOS.length >= 1)
	{
		// Cycle Videos
		$.each(VIDEOS, function(i, val)
		{
			var rating = Math.ceil(val.rating_average);

			// Display Rating
			switch(rating)
			{				
				case 1:
					var ratingHtml = '<span>*</span><span class="off"/><span class="off"/><span class="off"/><span class="off"/>';
				break;
				case 2:
					var ratingHtml = '<span>*</span><span>*</span><span class="off"/><span class="off"/><span class="off"/>';
				break;
				case 3:
					var ratingHtml = '<span>*</span><span>*</span><span>*</span><span class="off"/><span class="off"/>';
				break;
				case 4:
					var ratingHtml = '<span>*</span><span>*</span><span>*</span><span>*</span><span class="off"/>';
				break;
				case 5:
					var ratingHtml = '<span>*</span><span>*</span><span>*</span><span>*</span><span>*</span>';
				break;
				default:
					var ratingHtml = '<span class="off"/><span class="off"/><span class="off"/><span class="off"/><span class="off"/>';
			}

			var html = '<li>\
						<div class="thumbnail"><img alt="'+val.title+'" src="'+val.thumbnail+'"/>\
							<p class="duration">'+convertSeconds(val.duration)+'</p>\
						</div>\
						<p class="title">'+val.title.substr(0, 15)+'...</p>\
						<p class="author">'+val.author_name.substr(0, 15)+'...</p>\
						<p class="rating">'+ratingHtml+'</p>\
					</li>';
						
			$('#videos .videoList ul').append(html);
			$('#videos .videoList ul li:last').click(function(){ playVideo(val); return false; });
		});
		
		switch(lang)
		{
			case 'en':
				$('#mainVideoContainer p').html('Please select a video from the right to play...');
				break;
			case 'fr':
				$('#mainVideoContainer p').html('Veuillez s&#233;lectionner une vid&#233;o &#224; droite pour la voir...');
				break;
			case 'de':
				$('#mainVideoContainer p').html('W&#228;hle rechts ein Video aus um es abzuspielen...');
				break;
		}				
	}
	else
	{
		switch(lang)
		{
			case 'en':
				$('#mainVideoContainer p').html('Sorry, no videos have been found...');
				break;
			case 'fr':
				$('#mainVideoContainer p').html('D&#233;sol&#233;, aucune vid&#233;o n`a pu &#234;tre trouv&#233;e...');
				break;
			case 'de':
				$('#mainVideoContainer p').html('W&#228;hlen Sie bitte rechts ein video aus, um es abzuspielen...');
				break;
		}
		
	}
}

// Fetch videos
function fetchPlaylist(callback)
{
	switch(lang)
	{
		case 'fr':
			var url = 'http://gdata.youtube.com/feeds/api/playlists/47BB56C2A8142AED';
			break;
		case 'de':
			var url = 'http://gdata.youtube.com/feeds/api/playlists/6946481F72352CF4';
			break;
		case 'en':
		default:
			var url = 'http://gdata.youtube.com/feeds/api/playlists/F1BF29B1E3A1D52E';
			break;
	}

	_IG_FetchXmlContent(url , function(response){
		if (response != null)
		{
			callback(response);
		}
		else
		{
			callback('error');
		}
	});
}

// Convert seconds to minutes
function convertSeconds(secs) {
	secVar0 = secs;                           // The initial data, in seconds
	var minVar = Math.floor(secVar0/60);  	// The minutes
	var secVar = secVar0 % 60;              	// The balance of seconds
	switch (minVar.toString().length) 
	{
		case 0:
			mins = "00";
		break;
		case 1:
			mins = "0" + minVar;
		break;
		default:
			mins = minVar;
		break;
	}
	switch (secVar.toString().length) 
	{
		case 0:
			secs = "00";
		break;
		case 1:
			secs = "0" + secVar;
		break;
		default:
			secs = secVar;
		break;
	}
	return mins + ":" + secs;
}

function isdefined(variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}


// Get Poll Questions
function getQuestions(refresh)
{
	hidePolls();

	if (questionsResponse == '' || refresh == true)
	{
		now = new Date();
		var url = 'http://utube-eu-elections.appspot.com/questions/get/locale/en/timestamp/'+now.getTime();
		
		_IG_FetchContent(url , function(response){
			response = eval('('+response+')');

			if (response.Success == 1)
			{
				questionsResponse = response;
				$('.pollPanel .loader').hide();
				showPoll(currentPoll);
			}
			else
			{
				$('.pollPanel.loader').html('Oops, there was a problem...');
			}
		}, /*{ refreshInterval: (60 * 10) }*/{ refreshInterval: (0) });
	}
	else
	{
		showPoll(currentPoll);
	}
}

function hidePolls()
{
	$('#poll ol li').removeClass('active');
}

// Change Poll
function showPoll(poll)
{
	if (questionsResponse != '')
	{
		currentPoll = poll;
		hidePolls();
		switch(currentPoll)
		{
			case 0:
				var id = "q1";
				switch(lang)
				{
					case 'en':
						_IG_EmbedFlash('http://www.youtube.com/v/Ep5D1XSmMz8', 'qvid', {width: 267, height: 200});
						break;
					case 'fr':
						_IG_EmbedFlash('http://www.youtube.com/v/qVT2gre2VZM', 'qvid', {width: 267, height: 200});
						break;
					case 'de':
						_IG_EmbedFlash('http://www.youtube.com/v/eEryiv-1nxw', 'qvid', {width: 267, height: 200});
						break;
				}
				break;
			case 1:
				var id = "q2";
				switch(lang)
				{
					case 'en':
						_IG_EmbedFlash('http://www.youtube.com/v/SSEmJ3PaVj0', 'qvid', {width: 267, height: 200});
						break;
					case 'fr':
						_IG_EmbedFlash('http://www.youtube.com/v/RAywo53NH64', 'qvid', {width: 267, height: 200});
						break;
					case 'de':
						_IG_EmbedFlash('http://www.youtube.com/v/w1yuuXppCV', 'qvid', {width: 267, height: 200});
						break;
				}
				break;
			case 2:
				var id = "q3";
				switch(lang)
				{
					case 'en':
						_IG_EmbedFlash('http://www.youtube.com/v/uDNJmTKsKqc', 'qvid', {width: 267, height: 200});
						break;
					case 'fr':
						_IG_EmbedFlash('http://www.youtube.com/v/kmomksfaX1E', 'qvid', {width: 267, height: 200});
						break;
					case 'de':
						_IG_EmbedFlash('http://www.youtube.com/v/PUIl652MB90', 'qvid', {width: 267, height: 200});
						break;
				}
				break;
			case 3:
				var id = "q4";
				switch(lang)
				{
					case 'en':
						_IG_EmbedFlash('http://www.youtube.com/v/PrEuWRx9gwg', 'qvid', {width: 267, height: 200});
						break;
					case 'fr':
						_IG_EmbedFlash('http://www.youtube.com/v/H3HmVWW1SEg', 'qvid', {width: 267, height: 200});
						break;
					case 'de':
						_IG_EmbedFlash('http://www.youtube.com/v/QU4meshvtwg', 'qvid', {width: 267, height: 200});
						break;
				}
				break;
		}

		$('#'+id).addClass('active')

		

		for(var l=0; l<questionsResponse.Questions[currentPoll].Answers.length; l++)
		{
			switch(questionsResponse.Questions[currentPoll].Answers[l].Text)
			{
				case 'yes':
					$('#'+id+' .yes h5').html(generatePercentHtml(questionsResponse.Questions[currentPoll].Answers[l].Percent));
					$('#'+id+' .yes .result').html('')
					var yesHtml = '';
			
					for(var i=1; i<=questionsResponse.Questions[currentPoll].Answers[l].Percent; i++)
					{
						yesHtml += '<span />';
					}
					$('#'+id+' .yes .result').html(yesHtml);
					
					break;
				case 'no':
					$('#'+id+' .no h5').html(generatePercentHtml(questionsResponse.Questions[currentPoll].Answers[l].Percent));
					$('#'+id+' .no .result').html('')
					var noHtml = '';
			
					for(var q=1; q<=questionsResponse.Questions[currentPoll].Answers[l].Percent; q++)
					{
						noHtml += '<span />';
					}
					$('#'+id+' .no .result').html(noHtml);

					break;
			}
		}

		if(votedPolls[currentPoll] == 0)
		{
			// Set vote button events
			$('#'+id+' .yes a').unbind('click').click(function(){votePoll(questionsResponse.Questions[currentPoll].Id, 'yes', id)});
			$('#'+id+' .no a').unbind('click').click(function(){votePoll(questionsResponse.Questions[currentPoll].Id, 'no', id)});
		}
	}

	return false;
}

// Generate percentage html
function generatePercentHtml(percent)
{
	val = percent.toString().split('').reverse();
	var	html = '<span class="percent">%</span>';

	html += '<span class="number'+val[0]+'">'+val[0]+'</span>';

	if (percent > 9)
	{
		html += '<span class="number'+val[1]+'">'+val[1]+'</span>';
	}
	
	if (percent == 100)
	{
		html += '<span class="number1">1</span>';
	}	

	return html;	
}

// Vote for Poll
function votePoll(id, answer, container)
{
	var url = 'http://utube-eu-elections.appspot.com/questions/vote/q/'+id+'/a/'+answer+'/timestamp/'+now.getTime();
	
	hidePolls();
	$('.pollPanel .loader').fadeIn(200);

	_IG_FetchContent(url , function(response){
		response = eval('('+response+')');
		if (response.Success == 1)
		{
			$('#'+container+' .vote h4').fadeTo('slow', 0.4);
			$('#'+container+' .vote h4 a').unbind('click').css('cursor', 'pointer')

			votedPolls[currentPoll] = 1;

			switch(currentPoll)
			{
				case 0:
					currentPoll = 1;
					break;
				case 1:
					currentPoll = 2;
					break;
				case 2:
					currentPoll = 3;
					break;
				default:
					currentPoll = 0;
					break;
			}

			getQuestions(true);
		}
		else
		{
			console.log('Oops, there was a problem...');
		}
	});

	return false;
}
